package server;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;

/**
 * Created by Михаил on 21.05.14.
 */
public class serv {
    public static void main(String[] args) throws IOException {
        String host = "localhost";
        int port = 6666;
        ServerSocket serverSocket = new ServerSocket(port);
        System.out.println("Ожидание игроков");
        try {
            Socket s1 = serverSocket.accept();
            Socket s2 = new Socket();
            System.out.println("Ожидание второго игрока");
            while ((!s1.isConnected())||(!s2.isConnected())) {
                if (!s1.isConnected()) s1 = serverSocket.accept();
                else if (s1.isClosed()) s1 = serverSocket.accept();
                if (!s2.isConnected()) s2 = serverSocket.accept();
                else if (s2.isClosed()) s2 = serverSocket.accept();
            }
            System.out.println("Соединение установлено");
            DataInputStream dis1 = new DataInputStream(s1.getInputStream());
            DataInputStream dis2 = new DataInputStream(s2.getInputStream());
            DataOutputStream dos1 = new DataOutputStream(s1.getOutputStream());
            DataOutputStream dos2 = new DataOutputStream(s2.getOutputStream());
            // Первый - Х, второй - О.
            dos1.writeBoolean(true);
            dos2.writeBoolean(false);
            DataInputStream curDis = dis1;
            DataOutputStream curDos = dos2;
            while ((s1.isConnected())&&(s2.isConnected())&&(!s1.isClosed())&&(!s2.isClosed())) {
                String input = curDis.readUTF();
                String[] res = input.split(" ");
                if (!(res[1].equals("false")))
                    curDos.writeUTF(input);
                if (res[0].equals("true")) {
                    curDis = dis2;
                    curDos = dos1;
                }
                else {
                    curDis = dis1;
                    curDos = dos2;
                }
            }
        } catch (SocketException ex) {
            System.out.println("Соединение было прервано");
        }
    }

}